﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace MVVMFramework.View
{
    public class DateTimeConverter : ConverterBase
    {
        public DateTimeConverterMode Mode
        {
            get;
            set;
        }

        protected override bool GetReversedValue(object value, Type targetType, out object reversedValue)
        {
            if (value is DateTime)
            {
                DateTime dt = (DateTime)value;
                if (Mode == DateTimeConverterMode.ToLocal)
                {
                    reversedValue = dt.ToUniversalTime();
                    return true;
                }

                if (Mode == DateTimeConverterMode.ToUTC)
                {
                    reversedValue = dt.ToLocalTime();
                    return true;
                }
            }

            reversedValue = null;
            return false;
        }

        protected override object TryConvert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            if (!(value is DateTime))
                throw new Exception("Unexpected value type");

             DateTime dt = (DateTime)value;
            if (Mode == DateTimeConverterMode.ToLocal)
                return dt.ToLocalTime();

            if (Mode == DateTimeConverterMode.ToUTC)
                return dt.ToUniversalTime();

            throw new ConverterException(string.Format("Unexpected conversion mode {0}", Mode));
        }

        protected override object TryConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            if (!(value is DateTime))
                throw new Exception("Unexpected value type");

            DateTime dt = (DateTime)value;
            if (Mode == DateTimeConverterMode.ToLocal)
                return dt.ToUniversalTime();

            if (Mode == DateTimeConverterMode.ToUTC)
                return dt.ToLocalTime();

            throw new ConverterException(string.Format("Unexpected conversion mode {0}", Mode));
        }
    }
}
